package demo.java.lang.management.jvm;

import demo.java.lang.management.vo.MemoryPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;

/**
 * 收集jvm各个区使用信息
 * @date 16/1/15
 */
public class MemoryPoolCollector {
    private static final Logger logger = LoggerFactory.getLogger(MemoryPoolCollector.class);

    private List<MemoryPoolMXBean> memoryPoolMXBeans;

    public MemoryPoolCollector(List<MemoryPoolMXBean> memoryPoolMXBeans) {
        this.memoryPoolMXBeans = memoryPoolMXBeans;
    }


    public List<MemoryPool> collect() {
        List<MemoryPool> memoryPools = new ArrayList<MemoryPool>();

        try {
            for (MemoryPoolMXBean pool : this.memoryPoolMXBeans) {
                MemoryUsage usage = pool.getUsage();

                MemoryPool poolInfo = new MemoryPool();
                poolInfo.setName(pool.getName());
                poolInfo.setInit(usage.getInit());
                poolInfo.setMax(usage.getMax());
                poolInfo.setCommitted(usage.getCommitted());
                poolInfo.setUsed(usage.getUsed());
                poolInfo.setPeakUsed(pool.getPeakUsage().getUsed());


                if (pool.isCollectionUsageThresholdSupported()) {
                    poolInfo.setCollectionUsed(pool.getCollectionUsage().getUsed());
                }
                memoryPools.add(poolInfo);
                pool.resetPeakUsage();
            }
        }catch (Throwable e){
            logger.error("MemoryPoolCollector collect error, {}", e.getMessage());
            return null;
        }

        return memoryPools;
    }


}
